<?php

declare(strict_types=1);

namespace app\lnk\model;

use lite\model\BaseModel;
use lite\service\FileService;
use think\facade\Db;

class IntegralModel extends BaseModel
{
    protected $name = 'sns_user_integral';

    protected $type = [

    ];

    protected $json = [];    // 自动 json 转换

    public function user()
    {
        return $this->hasOne(UserModel::class, "id", "user_id")->field("id,name,avatar");
    }

    public function integral_save($uid, $title, int $number, $type)
    {
        $this->insert([
            'user_id' => $uid,
            'title' => $title,
            'number' => $number,
            'type' => $type,
            'create_time' => time()
        ]);
        
        if ($type == 1) {
            UserModel::where('id', $uid)
                ->inc('integral_all', $number)
                ->inc('integral_usable', $number)
                ->update();
        } else {
            UserModel::where('id', $uid)
                ->inc('integral_used', $number)
                ->dec('integral_usable', $number)
                ->update();
        }
    }
}
